package com.aitaoxue.palx.fragment;

import java.util.Map;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.aitaoxue.palx.R;
import com.aitaoxue.palx.adapter.BlogAdapter;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.ListBaseAdapter;
import com.aitaoxue.palx.base.NoCacheBaseListFragment;
import com.aitaoxue.palx.bean.Blog;
import com.aitaoxue.palx.bean.BlogList;
import com.aitaoxue.palx.bean.ListEntity;
import com.aitaoxue.palx.util.GsonUtil;

public class LogFragment extends NoCacheBaseListFragment {
	private Blog lastBlog = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = super.onCreateView(inflater, container, savedInstanceState);
		if (LocalLog) {
			view.findViewById(R.id.log_title).setVisibility(View.GONE);
		}

		return view;
	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_blog;
	}

	@Override
	protected ListBaseAdapter getListAdapter() {
		return new BlogAdapter();
	}

	@Override
	protected void sendRequestData(Map<String, String> map) {
		if (LocalLog) {
			AitaoXueApi.showOrderRecords(orderId, String.valueOf(mCurrentPage),
					mCacheHandler);
		} else {
			AitaoXueApi.getProdAllRecords(String.valueOf(mCurrentPage),
					mCacheHandler);
		}
	}

	@Override
	protected ListEntity parseList(byte[] response) throws Exception {
		String result = new String(response);

		BlogList blogList = GsonUtil.GsonToBean(result, BlogList.class);

		return blogList;
	}

	@Override
	public void onItemClick(AdapterView<?> parentView, View view, int position,
			long arg3) {
		Blog blog = (Blog) mAdapter.getItem(position);
		((TextView) view.findViewById(R.id.blog_content)).setText(blog
				.getRecord_content());

		int start = mListView.getFirstVisiblePosition();
		for (int i = start, j = mListView.getLastVisiblePosition(); i <= j; i++) {
			if (lastBlog != null && lastBlog != blog
					&& lastBlog == mListView.getItemAtPosition(i)) {
				View lastView = mListView.getChildAt(i - start);
				if (lastBlog.getRecord_content().length() > 30) {
					((TextView) lastView.findViewById(R.id.blog_content))
							.setText(lastBlog.getRecord_content().substring(0,
									30)
									+ "...点击查看全部");
				} else {
					((TextView) lastView.findViewById(R.id.blog_content))
							.setText(lastBlog.getRecord_content());
				}
			}
		}

		lastBlog = blog;
	}

	public static LogFragment newInstance(String orderid) {
		Bundle bundle = new Bundle();
		bundle.putString("orderid", orderid);

		LogFragment fragment = new LogFragment();
		fragment.setArguments(bundle);
		return fragment;
	}
}
